﻿using Controller.Model;
using PickingGuide.Enum;
using PickingGuide.Handle;
using PickingGuide.Model;
using ScanConfirmForm;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Application = System.Windows.Forms.Application;

namespace PickingGuideForm
{
    public partial class Form1 : Form
    {
        PickingGuideHandler pickingGuideHandler;
        List<ManualSetupModel> Queues = new List<ManualSetupModel>();

        public Form1()
        {
            InitializeComponent();
        }

        List<UIPanel> list = new List<UIPanel>();

        private void Form1_Load(object sender, EventArgs e)
        {
            pickingGuideHandler = PickingGuideHandler.getInstance();
            pickingGuideHandler.OnWorkGuideChange += WorkGuideRefresh;
            pickingGuideHandler.OnWorkQueueChange += DgvRefresh;
            pickingGuideHandler.OnRackChange += OnFlowLayoutPanelRefresh;
            pickingGuideHandler.MesgNotificationEvent += MesgShow;
            pickingGuideHandler.OnComplete += OnComplete;

            pickingGuideHandler.Init();

            dgvQueue.ClearSelection();
            dgvQueue.AutoGenerateColumns = false;
            dgvQueue.ReadOnly = true;
            //dgvQueue.AddColumn("连番", "Sequence", 12);
            dgvQueue.AddColumn("记号", "PartsCode1", 12);
            dgvQueue.AddColumn("车身码", "BodyNum", 17);
            dgvQueue.AddColumn("VIN", "VIN", 45);
            dgvQueue.AddColumn("车型", "CarModel", 22);
            dgvQueue.AddColumn("接收时间", "CreatedDate", 35);
            dgvQueue.RowHeight = 45;
            dgvQueue.ColumnHeadersHeight = 50;

            btnAuto.Enabled = false;
            btnManual.Enabled = true;
            btnManualInput.Enabled = false;

            uiPanel1.Text = pickingGuideHandler.SystemSetup.SystemName;
            uiPanel1.Refresh();

            if (this.WindowState == FormWindowState.Maximized)
            {
                //this.WindowState = FormWindowState.Normal;
            }
            else
            {
                //全屏
                //this.ShowFullScreen = true;
                this.WindowState = FormWindowState.Maximized;
            }
        }

        private void OnComplete()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                if (Queues != null && Queues.Count != 0)
                {
                    Queues.RemoveAt(0);
                }
            }));
        }

        private void WorkGuideRefresh(QueueInfoModel model)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                txtVIN.Text = model.VIN;
                txtBody.Text = model.BodyNum;
                txtCarCode.Text = model.CarModel;
                //txtSequence.Text = model.Sequence.ToString("000");
                txtCode.Text = pickingGuideHandler.GetRackName(model); ;
            }));
        }

        public void DgvRefresh(List<QueueInfoModel> queue)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                if (queue == null || queue.Count <= 0)
                {
                    dgvQueue.DataSource = null;
                }
                else
                {
                    dgvQueue.DataSource = null;
                    dgvQueue.DataSource = queue;
                }
                Dgv_Cells(ref dgvQueue);
            }));
        }

        public void OnFlowLayoutPanelRefresh(List<RackSetupModel> racks)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                //uiFlowLayoutPanel1.Clear();
                //uiFlowLayoutPanel2.Clear();
                //list.Clear();
                foreach (var item in racks)
                {
                    //
                    //1#大灯用Code，2#油箱用Name，还没统一处理，特此说明
                    //
                    //var panel = list.Where(x => x.Name == item.Code).FirstOrDefault();
                    var panel = list.Where(x => x.Name == item.Name).FirstOrDefault();
                    if (panel != null)
                        continue;
                    panel = new UIPanel();
                    panel.Size = new Size(100, 40);
                    panel.BackColor = Color.LightGray;
                    panel.FillColor = Color.LightGray;
                    //panel.ForeColor = Color.Green;
                    panel.Text = item.Name;
                    panel.Name = item.Name;
                    if (item.RackType == "1")
                        uiFlowLayoutPanel1.Add(panel);
                    else
                        uiFlowLayoutPanel2.Add(panel);
                    list.Add(panel);
                }
                foreach (UIPanel panel in list)
                {
                    if (racks.Where(x => x.Name == panel.Name).FirstOrDefault().Status == "1")
                    {
                        panel.BackColor = Color.DeepSkyBlue;
                        panel.FillColor = Color.DeepSkyBlue;
                    }
                    else if (racks.Where(x => x.Name == panel.Name).FirstOrDefault().Status == "2")
                    {
                        panel.BackColor = Color.LightGreen;
                        panel.FillColor = Color.LightGreen;
                    }
                    else
                    {
                        panel.BackColor = Color.LightGray;
                        panel.FillColor = Color.LightGray;
                    }
                }
            }));
        }

        public void Dgv_Cells(ref UIDataGridView dgv)
        {
            if (dgv.Rows.Count > 0)
                dgv.Rows[0].Selected = false;

            foreach (DataGridViewRow item in dgv.Rows)
            {
                var model = item.DataBoundItem as QueueInfoModel;
                if (model.Status == "ok")
                {
                    item.DefaultCellStyle.BackColor = Color.LightGray;
                }
                else if (model.Status == "work")
                {
                    item.DefaultCellStyle.BackColor = Color.LightGreen;
                }
                else if (model.Status == "unok")
                {
                    item.DefaultCellStyle.BackColor = Color.Red;
                }
                else if (model.Status == "pass")
                {
                    item.DefaultCellStyle.BackColor = Color.Yellow;
                }
                else
                {
                    item.DefaultCellStyle.BackColor = Color.White;
                }
            }
        }

        /// <summary>
        /// 实时消息显示
        /// </summary>
        /// <param name="mes">显示消息</param>
        /// <param name="index">消息类型(0错误信息；1正常信息)</param>
        private void MesgShow(string mes, MessageType messageType)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                if (messageType == MessageType.Error)
                    AppendTextColorful(this.txtInfo, mes, Color.Red, true);
                else if (messageType == MessageType.warning)
                    AppendTextColorful(this.txtInfo, mes, Color.Yellow, true);
                else
                    AppendTextColorful(this.txtInfo, mes, Color.Green, true);
            }));
        }

        /// <summary>
        /// 富文本框格式化方法
        /// </summary>
        /// <param name="rtBox">富文本框</param>
        /// <param name="addtext">添加文本内容</param>
        /// <param name="color">当前添加文本显示颜色</param>
        /// <param name="IsaddNewLine">是否换行</param>
        private void AppendTextColorful(RichTextBox rtBox, string addtext, Color color, bool IsaddNewLine)
        {
            if (IsaddNewLine)
            {
                addtext += Environment.NewLine;
            }
            rtBox.SelectionStart = rtBox.TextLength;
            rtBox.SelectionLength = 0;
            rtBox.SelectionColor = color;
            rtBox.AppendText(DateTime.Now.ToString() + "  " + addtext);
            rtBox.SelectionColor = rtBox.ForeColor;

            if (rtBox.Lines.Length > 5000)
            {
                DelSpecialLines(rtBox, 1, 500);//删除第 1 行
            }

            // 让光标定位到文本框末尾
            rtBox.Select(rtBox.TextLength, 0);

            //然后移动滚动条，使输入点(text entry point)(即光标所在的位置）显示出来
            //这样也可以达到滚动到最下方的目的
            rtBox.ScrollToCaret();

            rtBox.Refresh();
            rtBox.Focus();
        }

        /// <summary>
        /// 删除任意指定行
        /// </summary>
        /// <param name="startLineNum">开始行号</param>
        /// <param name="endLineNum">结束行号</param>
        private void DelSpecialLines(RichTextBox rtBox, int startLineNum, int endLineNum)
        {
            //获取指定行的第一行的第一个字符的索引
            int start = rtBox.GetFirstCharIndexFromLine(startLineNum - 1);

            //获取指定行的最后一行的第一个字符的索引
            int end = rtBox.GetFirstCharIndexFromLine(endLineNum);
            rtBox.Select(start, end - start);//选中指定行
            rtBox.SelectedText = "";//设置选择行的内容为空
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
            if (frmLogin.DialogResult == DialogResult.OK)
            {
                if (pickingGuideHandler.User.Permission == 0)
                {
                    var mesg = "用户(" + pickingGuideHandler.User.LoginName + ")操作：关闭软件！";
                    MesgShow(mesg, MessageType.Info);
                    pickingGuideHandler.Close();

                    //pickingGuideHandler.LogInfo(mesg);
                    Application.Exit();
                }
                else
                {
                    var mesg = "用户(" + pickingGuideHandler.User.LoginName + ")操作：关闭软件禁止！禁止原因：无此权限！";
                    MesgShow(mesg, MessageType.Error);
                    //pickingGuideHandler.LogError(mesg);
                    MessageBox.Show("该用户权限无法进行此操作！");
                }
            }
        }

        private void btnSetup_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
            if (frmLogin.DialogResult == DialogResult.OK)
            {
                if (pickingGuideHandler.User.Permission == 0)
                {
                    FrmSetup frmSetup = new FrmSetup();
                    frmSetup.ShowDialog();
                }
                else
                {
                    var mesg = "用户(" + pickingGuideHandler.User.LoginName + ")操作：系统设置禁止！禁止原因：无此权限！";
                    MesgShow(mesg, MessageType.Error);
                    //pickingGuideHandler.LogError(mesg);
                    MessageBox.Show("该用户权限无法进行此操作！");
                }
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            FrmHistory frmHistory = new FrmHistory();
            frmHistory.Show();
        }


        private void btnAuto_Click(object sender, EventArgs e)
        {
            if (pickingGuideHandler.IsSuspend || !pickingGuideHandler.SystemSetup.SuspendActivate)
            {
                btnAuto.Enabled = false;
                btnManual.Enabled = true;
                btnManualInput.Enabled = false;
                pickingGuideHandler.ManualToAuto();
            }
            else
            {
                MessageBox.Show("请先暂停作业，再切换手动模式！");
                return;
            }
        }

        private void btnManual_Click(object sender, EventArgs e)
        {
            if (pickingGuideHandler.IsSuspend || !pickingGuideHandler.SystemSetup.SuspendActivate)
            {

            }
            else
            {
                MessageBox.Show("请先暂停作业，再切换手动模式！");
                return;
            }

            DialogResult begin = MessageBox.Show("确定要切换至手动模式？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (!(begin == DialogResult.Yes))
            {
                return;
            }
            Queues = new List<ManualSetupModel>();
            btnAuto.Enabled = true;
            btnManual.Enabled = false;
            btnManualInput.Enabled = true;
            dgvQueue.DataSource = null;
            pickingGuideHandler.AutoToManual(Queues);
        }

        private void btnManualInput_Click(object sender, EventArgs e)
        {
            FrmManualInput frm = new FrmManualInput(Queues);
            frm.RefreshUiEvent += pickingGuideHandler.AutoToManual;
            frm.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (pickingGuideHandler.IsSuspend && pickingGuideHandler.SystemSetup.SuspendActivate)
            {
                MessageBox.Show("暂停作业，无法调至下一个连番！");
                return;
            }
            DialogResult begin = MessageBox.Show("确定要完成该连番并跳至下一连番？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (!(begin == DialogResult.Yes))
            {
                return;
            }
            pickingGuideHandler.CompleteToNext();
        }

        private void btnSuspend_Click(object sender, EventArgs e)
        {
            if (pickingGuideHandler.IsSuspend)
            {
                if(dgvQueue.Rows.Count<=0)
                {
                    MessageBox.Show("作业队列为空，无法开始作业！");
                    return;
                }
                var result = pickingGuideHandler.Suspend();
                if (result)
                {
                    btnSuspend.Text = "作业开始";
                }
                else
                {
                    btnSuspend.Text = "作业暂停";
                }
            }
            else
            {
                FrmLogin frmLogin = new FrmLogin();
                frmLogin.ShowDialog();
                if (frmLogin.DialogResult == DialogResult.OK)
                {
                    if (pickingGuideHandler.User.Permission == 0)
                    {
                        var result = pickingGuideHandler.Suspend();
                        if (result)
                        {
                            btnSuspend.Text = "作业开始";
                        }
                        else
                        {
                            btnSuspend.Text = "作业暂停";
                        }
                    }
                    else
                    {
                        var mesg = "用户(" + pickingGuideHandler.User.LoginName + ")操作：系统设置禁止！禁止原因：无此权限！";
                        MesgShow(mesg, MessageType.Error);
                        //pickingGuideHandler.LogError(mesg);
                        MessageBox.Show("该用户权限无法进行此操作！");
                    }
                }
            }
        }

        private void dgvQueue_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                e.FormattingApplied = true;
                if(dgvQueue.Rows.Count >= (e.RowIndex+1))
                {
                    DataGridViewRow row = dgvQueue.Rows[e.RowIndex];
                    if (row != null)
                    {
                        var model = dgvQueue.Rows[e.RowIndex].DataBoundItem as QueueInfoModel;

                        if (pickingGuideHandler.pickingType == PickingType.Auto)
                        {
                            var name = pickingGuideHandler.GetRackCode(model);
                            e.Value = string.Format("{0}",
                                  name);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(model.Remark))
                            {
                                var ids = model.Remark.Split(',');
                                long id;
                                if (long.TryParse(ids[0], out id))
                                {
                                    var name = pickingGuideHandler.GetRackCode(id);
                                    e.Value = string.Format("{0}",
                                          name);
                                }
                                else
                                {
                                    e.Value = string.Format("{0}",
                                         "无配置");
                                }
                            }
                        }
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            TriggerLabelPacketModel iModel = new TriggerLabelPacketModel();
            iModel.Address = textBox1.Text.Trim();
            pickingGuideHandler.AioiControllerButtonEvent(iModel);
        }

        private void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
    }
}
